package com.alibaba.citrus.cr.forecast.facade.service;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.forecast.facade.converter.QueryForecastRequestConverter;
import com.alibaba.citrus.cr.forecast.functions.forecastorder.ability.ForecastOrderLineAbility;
import com.alibaba.citrus.cr.forecast.repository.ForecastOrderLineQueryRepository;
import com.alibaba.citrus.cr.forecast.repository.ForecastOrderQueryRepository;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crforecastsales.api.forecastorderquery.dto.QueryForecastActivityDetailsRequest;
import com.epoch.app.crforecastsales.api.forecastorderquery.service.ForecastOrderQueryService;
import com.epoch.app.crforecastsales.dto.request.DealForecastListRequest;
import com.epoch.app.crforecastsales.dto.request.QueryForecastOrderDetailRequest;
import com.epoch.app.crforecastsales.dto.request.QueryForecastRequest;
import com.epoch.app.crforecastsales.dto.response.DealForecastOrderResponse;
import com.epoch.app.crforecastsales.dto.response.QueryForecastOrderDetailReponse;
import com.epoch.app.crforecastsales.model.dto.ForecastOrderActivitiesResponse;
import com.epoch.app.crforecastsales.model.dto.ForecastOrderActivityRequest;
import com.epoch.app.crforecastsales.model.dto.ForecastOrderActivityResponse;
import com.epoch.app.crforecastsales.model.dto.PageQueryForecastLineRequest;
import com.epoch.app.crforecastsales.sdo.ForecastOrderLineSDO;
import com.epoch.app.crforecastsales.sdo.ForecastOrderSDO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Primary
public class ForecastOrderQueryServiceImpl implements ForecastOrderQueryService {
    private Log log = Log.getLogger(ForecastOrderQueryServiceImpl.class);
    @Resource
    ForecastOrderQueryRepository forecastOrderQueryRepository;

    @Resource
    ForecastOrderLineAbility forecastOrderLineAbility;

    @Resource
    ForecastOrderLineQueryRepository forecastOrderLineQueryRepository;

    @Override
    @FacadeInvoker
    public Result<QueryForecastOrderDetailReponse> queryForecastOrder(QueryForecastOrderDetailRequest queryForecastOrderDetailRequest) {
        //返回结果`
        QueryForecastOrderDetailReponse queryForecastOrderDetailReponse = new QueryForecastOrderDetailReponse();
        String orderId = queryForecastOrderDetailRequest.getId();
        ForecastOrderSDO forecastOrderSDO = forecastOrderQueryRepository.queyrDetail(orderId);
        ForecastOrderLineSDO tmp = new ForecastOrderLineSDO();
        tmp.setMainOrderId(orderId);
        List<ForecastOrderLineSDO> forecastOrderLineSDOResultList= forecastOrderLineQueryRepository.queyrLineDetailList(tmp);
        //累计金额 数量
        long totalFee = 0L;
        int quantity = 0;
        if (CollectionUtils.isNotEmpty(forecastOrderLineSDOResultList)){

            for (ForecastOrderLineSDO lineSDO : forecastOrderLineSDOResultList) {
                if (StringUtils.isNotBlank(lineSDO.getQuantity())) {
                    totalFee += lineSDO.getUnitPrice() * Integer.parseInt(lineSDO.getQuantity());
                    quantity += Integer.parseInt(lineSDO.getQuantity());
                }
            }
            forecastOrderSDO.setOrderTotalFee(totalFee);
            forecastOrderSDO.setTotalPredictAmount(quantity);
        }

        forecastOrderSDO.setForecastOrderLineSDOList(forecastOrderLineSDOResultList);
        //返回结果
        queryForecastOrderDetailReponse.setForecastOrderSDO(forecastOrderSDO);
        return Result.success(queryForecastOrderDetailReponse);
    }

    /**
     * 分页查询预报订单列表  袁登
     *
     * @param queryForecastRequest
     * @return
     */
    @Override
    public Result<List<ForecastOrderSDO>> pageQuery(QueryForecastRequest queryForecastRequest) {
        try{
            ForecastOrderSDO forecastOrderSDO = QueryForecastRequestConverter.toQueryForecastResponse(queryForecastRequest);
            PageResult<List<ForecastOrderSDO>> pageResult = forecastOrderQueryRepository.pageQuery(forecastOrderSDO);
            Result<List<ForecastOrderSDO>> success = Result.success(pageResult.getContent());
            success.setTotal(pageResult.getTotal());
            return success;
        }catch (Exception e){
            log.error("查询预报订单列表异常:",e);
            throw new FunctionException("OTS-04-001-00-15-006");
        }
    }
    @FacadeInvoker
    @Override
    public Result<List<DealForecastOrderResponse>> queryDealForecastList(DealForecastListRequest dealForecastListRequest) {
        //根据订单明细Id查询出来订单明细信息
//        List<Long> nowIds = dealForecastListRequest.getNowIds();
//        if(CollectionUtils.isNotEmpty(nowIds)) {
//            List<String> ids = new ArrayList<>();
//            for (Long pk : nowIds) {
//                ForecastOrderEntity forecastOrderEntitiy = ForecastOrderFactory.loadById(String.valueOf(pk));
//                List<String> id = forecastOrderEntitiy.totalReplyNumber();
//                ids.addAll(id);
//            }
//            dealForecastListRequest.setNowLineIds(ids);
//        }
        List<DealForecastOrderResponse> dealForecastOrderResponses = forecastOrderLineQueryRepository.loadDealForecastListV2(dealForecastListRequest);
        return Result.success(dealForecastOrderResponses);
    }

    @Override
    @FacadeInvoker
    public Result<List<ForecastOrderActivitiesResponse>> queryActivityForecast(
        ForecastOrderActivityRequest forecastOrderActivityRequest) {
        log.info("预报查询活动入参Request："+JSONObject.toJSONString(forecastOrderActivityRequest));
        List<ForecastOrderActivitiesResponse> forecastOrderActivityResponses = forecastOrderLineAbility.queryActivity(forecastOrderActivityRequest);
        List<ForecastOrderActivitiesResponse> sortResultList = sortBizOrderId(forecastOrderActivityResponses);
        log.info("预报查询活动返回值Response："+JSONObject.toJSONString(sortResultList));
        return Result.success(sortResultList);
    }
    @Override
    @FacadeInvoker
    public Result<List<ForecastOrderActivityResponse>> queryActivityForecastObsolete(ForecastOrderActivityRequest forecastOrderActivityRequest) {
        log.info("预报查询活动入参Request："+JSONObject.toJSONString(forecastOrderActivityRequest));
        List<ForecastOrderActivityResponse> forecastOrderActivityResponses = forecastOrderLineAbility.queryActivityObsolete(forecastOrderActivityRequest);
        List<ForecastOrderActivityResponse> sortResultList = sortBizOrderIdObsolete(forecastOrderActivityResponses);
        log.info("预报查询活动返回值Response："+JSONObject.toJSONString(sortResultList));
        return Result.success(sortResultList);
    }

    private List<ForecastOrderActivitiesResponse> sortBizOrderId(List<ForecastOrderActivitiesResponse> forecastOrderActivityResponses) {
       return Nullable.stream(forecastOrderActivityResponses).sorted(
               Comparator.comparing(ForecastOrderActivitiesResponse::getOrderBizId).thenComparing(ForecastOrderActivitiesResponse::getForecastOrderLineId))
               .collect(Collectors.toList());

    }
    private List<ForecastOrderActivityResponse> sortBizOrderIdObsolete(List<ForecastOrderActivityResponse> forecastOrderActivityResponses) {
       return Nullable.stream(forecastOrderActivityResponses).sorted(Comparator.comparing(ForecastOrderActivityResponse::getOrderBizId).thenComparing(ForecastOrderActivityResponse::getForecastOrderLineId)).collect(Collectors.toList());

    }

    @Override
    public  Result<List<ForecastOrderActivityResponse>> queryForecastActivityDetails(QueryForecastActivityDetailsRequest queryForecastActivityDetailsRequest){
       List<ForecastOrderActivityResponse> forecastOrderActivityResponses=new ArrayList<>();
        log.info("预报查询活动详情入参Request：",queryForecastActivityDetailsRequest);
        ForecastOrderActivityResponse forecastOrderActivityResponse = forecastOrderLineAbility.queryActivityDetails(queryForecastActivityDetailsRequest);
        log.info("查询活动详情返回值Response", JSONObject.toJSONString(forecastOrderActivityResponse));
        forecastOrderActivityResponses.add(forecastOrderActivityResponse);
        return Result.success(forecastOrderActivityResponses);
    }

    @Override
    @Deprecated
    public Result<List<ForecastOrderSDO>> pageQueryByEs(PageQueryForecastLineRequest pageQueryForecastLineRequest){
        PageResult<List<ForecastOrderSDO>> listPageResult = forecastOrderQueryRepository.pageQueryByEs(pageQueryForecastLineRequest);
        Result<List<ForecastOrderSDO>> success = Result.success(listPageResult.getContent());
        success.setTotal(listPageResult.getTotal());
        return success;
    }

    // 此方法若与0925分支发生冲突，以bugfix分支为准。（0925分支代码会删掉）
    @FacadeInvoker
    @Override
    public Result<List<DealForecastOrderResponse>> queryRefuseDealForecastList(DealForecastListRequest dealForecastListRequest) {
        log.info("queryRefuseDealForecastList|批量拒绝查询入参:",JSONObject.toJSONString(dealForecastListRequest));
        List<DealForecastOrderResponse> dealForecastOrderResponses = forecastOrderLineQueryRepository.loadDealForecastListV3(dealForecastListRequest);
        return Result.success(dealForecastOrderResponses);
    }
}
